﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Input;
using DG.Common.EF.WPF;
using DG.Common.Patterns.Commands;
using DG.Common.Patterns.MVVM;
using TCC.ControleFluxoDeCaixa.Model.Contas;
using TCC.ControleFluxoDeCaixa.Model.Entities;
using TCC.ControleFluxoDeCaixa.Model.Fluxo;
using TCC.ControleFluxoDeCaixa.Model.Fluxo.TranferenciaEntreContas;

namespace TCC.ControleFluxoDeCaixa.Apresentacao.ViewModels
{
    public class TransferenciaEntreContasWindowViewModel : EntityCRUDViewModelBase<FluxoDeCaixaContextFiltrado, TransferenciaEntreContas>
    {
        //public readonly FluxoDeCaixaContext Context = FluxoContextFactory.GetInstance().Create();
        public IEnumerable<Categoria> GetCategorias
        {
            get { return Context != null ? Context.Categorias.ToArray() : null; }
        }

        public IEnumerable<ContaFinanceira> GetContas
        {
            get { return Context != null ? Context.ContaFinanceiras.ToArray() : null; }
        }

        public ICommand TransferirCommand
        {
            get
            {
                return new FunctionalCommand(() =>
                {
                    Transferencia();
                    SendMessage("Transferência Realizada com sucesso");
                    RaiseFinished();

                },() => Entity.ContaRemetente != null
                    && Entity.ContaDestinataria != null
                    && Entity.Valor != 0
                    && (Entity.ContaRemetente != Entity.ContaDestinataria));
            }
        }

        private void Transferencia()
        {
            var catTransf = Context.GetCategoriaTransferencia();
            var lancamentoEntrada = Entity.TransferenciaEntrada(catTransf);
            var lancamentoSaida = Entity.TransferenciaSaida(catTransf);

            Context.Lancamentos.Add(lancamentoEntrada);
            Context.Lancamentos.Add(lancamentoSaida);
            Context.Transferencias.Add(Entity);
            Context.SaveChanges();
        }

        public ICommand CancelarCommand
        {
            get
            {
                return new FunctionalCommand(RaiseFinished);
            }
        }

        protected override void AfterSetAction()
        {
            base.AfterSetAction();
            if (Action == CRUDOperationType.Create)
            {
                Entity.Usuario = Context.GetUsuarioLogado();
                Entity.DataTransferencia = DateTime.Now.Date;
            }
        }
    }
}
